<template>
  <px-select
    v-model="selectdValue"
    filterable
    remote
    clearable
    no-data-text="该机台不存在！"
    :loading="loading"
    :remote-method="remoteMethod"
    style="width: 100%"
    v-bind="{ ...$attrs }"
    @change="changeHandler"
  >
    <px-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
  </px-select>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { getFabList } from "@/api/modules/fab";

const options = ref<Array<any>>([]);
const loading = ref<boolean>(false);

const selectdValue = defineModel({ type: String, required: true, default: "" });

const emits = defineEmits(["change"]);

const remoteMethod = async (query: string) => {
  options.value.splice(0);
  if (query) {
    loading.value = true;
    let res = await getFabList(query);
    if (res?.length) {
      res = res.map(item => ({
        ...item,
        label: item.eqpId,
        value: item.eqpId
      }));
      options.value.push(...res);
    } else {
      options.value.push({
        value: query,
        label: query,
        isCustom: true,
        eqpId: query,
        eqpStatus: "RUN",
        // factoryId: "FAC_83abf9",
        model: null
      });
    }
    loading.value = false;
    return res;
  } else {
    options.value = [];
  }
};

const changeHandler = val => {
  if (options.value.length) {
    const t = options.value.find(item => item.label === val);
    t ? emits("change", t) : emits("change", null);
  } else {
    emits("change", null);
  }
};

defineExpose({
  remoteMethod,
  changeHandler
});
</script>
